import React, { useEffect, useImperativeHandle, forwardRef, useRef, useState, useContext } from "react"
import { Button } from "antd"
// 引入Context
import { TestContext } from '@/components/ContextComponents/TestContext'

interface MyComponentProps {
    inputVal: string,
    refInput: React.RefObject<HTMLInputElement>
}

const ChildTest = forwardRef(({ inputVal, refInput }: MyComponentProps, ref) => {

    useEffect(() => {
        if (inputVal) {
            console.log(`Input value from child: ${inputVal}`);
        }
    }, [inputVal])

    // 获取context提供的数据
    const level = useContext(TestContext)

    const { contextData, updateConetextData } = level

    console.log('666', level)

    const localRef = useRef<HTMLDivElement>(null)

    const [myObject, setMyObject] = useState({ key1: 'value1', key2: 'value2' });

    const updateObject = () => {
        setMyObject(prevState => ({
            ...prevState,
            key1: 'newValue1',
        }));
    };

    useEffect(() => {
        console.log('myObject updated:', myObject);
      }, [myObject]); // 在 myObject 变化时运行

    // 暴露当前组件的这个方法
    useImperativeHandle(ref, () => ({
        inputVal,
        refInput,
        someMethod() {
            console.log('Method called from Parent');
            if (localRef.current) {
                localRef.current.style.backgroundColor = 'yellow';
            }
        }
    }));

    const getParentInputValue = () => {
        console.log(refInput)
    }

    const updateContext = () => {
        updateConetextData?.()
    }

    return (
        <>
            <div ref={localRef}>子组件</div>
            <Button onClick={getParentInputValue}>获取父组件的input的值</Button>
            <br />
            <div>Key1: {myObject.key1}</div>
            <div>Key2: {myObject.key2}</div>
            <Button type="primary" onClick={updateObject}>changeObj</Button>
            <hr />
            <p>这是context提供的值Fun{contextData}</p>
            <Button onClick={updateContext}>change ContextValue</Button>
            <p>Parent Value：{inputVal}</p>
        </>
    )
})

export default ChildTest